package com.kit;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

public class CodecKit {
	private static final String CharCode = "UTF-8";
	// == Encode======================
	public static String encodeMd5(String str) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			String res = new BigInteger(1, md.digest()).toString(16);
			return getPadStr(32 - res.length(), "0") + res;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public static String getPadStr(int len, String def) {
		String ret = "";
		for (int i = 0; i < len; i++)
			ret += def;
		return ret;
	}

	public static String encodeHmacSha1(String src, String key) {
		try {
			SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(CharCode), "HmacSHA1");
			Mac mac = Mac.getInstance("HmacSHA1");
			mac.init(signingKey);
			byte[] rawHmac = mac.doFinal(src.getBytes(CharCode));
			return Hex.encodeHexString(rawHmac);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public static String encodeBase64(String plainText) {
		return encodeBase64(plainText.getBytes());
	}
	public static String encodeBase64(byte[] b) {
		Base64 base64 = new Base64();
		b = base64.encode(b);
		String s = new String(b);
		return s;
	}

	public static String encodeURL(String base64str) throws UnsupportedEncodingException {
		return java.net.URLEncoder.encode(base64str, CharCode);
	}
	// == Decode======================
	public static String decodeBase64(String encodeStr) {
		byte[] b = encodeStr.getBytes();
		Base64 base64 = new Base64();
		b = base64.decode(b);
		String s = new String(b);
		return s;
	}

}
